package com.yqkj.modules.sys.oauth2;

import com.yqkj.modules.sys.entity.SysUserEntity;
import com.yqkj.modules.sys.entity.SysUserTokenEntity;
import com.yqkj.modules.sys.service.ShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author wuyj
 * @email wuyj298@163.com
 * @date 2018年07月24 16:54
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private ShiroService shiroService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权（获取用户的权限）
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        SysUserEntity userEntity = (SysUserEntity) principal.getPrimaryPrincipal();
        Set<String> permissions = shiroService.getUserPermissions(userEntity.getUserId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;

    }

    /**
     * 认证（登录时调用）
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
        SysUserTokenEntity tokenEntity = shiroService.queryByToken(accessToken);
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token已失效，请重新登录");
        }

        SysUserEntity user = shiroService.queryUser(tokenEntity.getUserId());

        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定，请联系系统管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());

        return info;
    }
}
